<template>
  <div class="app-container">
    <div class="search-box">
      <el-button type="primary" @click="showDialog()">添加用户</el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="ID" width="60">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="头像" width="95">
        <template slot-scope="scope">
          <el-avatar :size="50" :src="scope.row.avatar" shape="square" ></el-avatar>
        </template>
      </el-table-column>
      <el-table-column label="用户名">
        <template slot-scope="scope">
          {{ scope.row.username }}
        </template>
      </el-table-column>
      
      <el-table-column class-name="status-col" label="角色"  align="center">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.role | roleFilter }}</el-tag>
        </template>
      </el-table-column>
      
      <el-table-column class-name="status-col" label="状态"  align="center">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.status | statusFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="登录时间">
        <template slot-scope="scope">
          {{ scope.row.last_login_time }}
        </template>
      </el-table-column>
      <el-table-column label="登录IP">
        <template slot-scope="scope">
          {{ scope.row.last_login_ip }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间">
        <template slot-scope="scope">
          {{ scope.row.create_time }}
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="操作"  align="center">
        <template slot-scope="scope">
          <el-link type="primary" @click="showDialog(scope.row)">编辑</el-link>
          <el-divider direction="vertical"></el-divider> 
          <el-link type="primary" @click="deleteConfirm(scope.row.id)">删除</el-link>
        </template>
      </el-table-column>
      
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
  
      <el-dialog title="新增/编辑用户" :visible.sync="dialogFormVisible">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="ruleForm.username" :disabled="disableUsername" ></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="ruleForm.password"  placeholder="新增必填，编辑时可不填" ></el-input>
          </el-form-item>
          <el-form-item label="角色" prop="role_id">
            <el-select v-model="ruleForm.role_id" placeholder="请选择角色">
              <el-option v-for="role in roles" :key="role.id" :label="role.name" :value="role.id"></el-option>
              
            </el-select>
          </el-form-item>
          
          <el-form-item label="状态" prop="delivery">
            <el-switch v-model="ruleForm.status"></el-switch>
          </el-form-item>

          <el-form-item label="头像">
            <el-upload
              class="avatar-uploader"
              :action="uploadApi"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
              <img v-if="ruleForm.avatar" :src="ruleForm.avatar" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>

          </el-form-item>
          
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
        </div>
      </el-dialog>
    </div>
</template>

<script>
import { userList,addUser,editUser,deleteUser } from '@/api/user'
import { getAllRole } from '@/api/role'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
export default {
  components: { Pagination },
  filters: {
    statusFilter(status) {
      if(status==1){
        return '正常'
      }else{
        return '禁用'
      }
    },
    roleFilter(role) {
      return role ? role.name : "无"
    }
  },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10
      },
      dialogFormVisible:false,
      ruleForm:{
          id:undefined,
          username:"",
          password:"",
          status:true,
          role_id:undefined,
          avatar:undefined,
      },
      rules: {
          
      },
      disableUsername:false,
      roles:[],
      uploadApi: `${process.env.VUE_APP_BASE_API}/admin/upload`,
    }
  },
  created() {
    this.getList()
    this.loadRoles()
  },
  methods: {
    loadRoles(){
      getAllRole().then(response => {
        this.roles = response.data.list
      })
    },
    getList() {
      this.listLoading = true
      userList(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        this.listLoading = false
      }).catch(err=>{
          console.log(err)
          this.listLoading = false
        })
    },
    showDialog(row){
      if(row){
        this.ruleForm.id = row.id
        this.ruleForm.username = row.username
        this.ruleForm.password = ""
        this.ruleForm.status = row.status
        this.ruleForm.role_id = row.role_id
        this.ruleForm.avatar = row.avatar
        this.disableUsername = true
      }else{
        this.ruleForm.id = undefined
        this.ruleForm.username = ""
        this.ruleForm.password = ""
        this.ruleForm.status = true
        this.ruleForm.role_id = undefined
        this.ruleForm.avatar = undefined
        this.disableUsername = false
      }
      this.dialogFormVisible = true;
      
    },
    submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let api = addUser
            if(this.ruleForm.id){
              api = editUser
            }
            api(this.ruleForm).then(response => {
              if(response.code==200){
                this.dialogFormVisible = false;
                this.getList()
              }
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      deleteConfirm(id){
        this.$confirm('真的要删除这条数据吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteUser({id}).then(response => {
              if(response.code==200){
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                });
                this.getList()
              }
            })
        }).catch(() => {
                    
        });
      },
      handleAvatarSuccess(res, file) {
        this.ruleForm.avatar = res.data.url
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 4;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 4MB!');
        }
        return isJPG && isLt2M;
      }
  }
}
</script>

<style scoped>
.search-box{
  padding-bottom: 10px;
}
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
</style>